﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Windows;
using System.Windows.Interactivity;
#if (WINRT)
using Windows.UI.Xaml;
using nRoute.Behaviors.Interactivity;
using Windows.UI.Xaml.Data;
#else
using nRoute.Components.TypeConverters;
#endif

namespace nRoute.Behaviors.Triggers
{
    public class ValueChangedTrigger
#if (WINRT)
        : TriggerBase<FrameworkElement>
#else
        : TriggerBase<DependencyObject>
#endif
    {
        public static readonly DependencyProperty SourceProperty =
            DependencyProperty.Register("Source", typeof(Object), typeof(ValueChangedTrigger), 
            new PropertyMetadata(Utilities.Compatability.DP_UNSET_VALUE, new PropertyChangedCallback(OnSourceChanged)));

#region Properties

        [Category("Common Properties")]
        [CustomPropertyValueEditor(CustomPropertyValueEditor.PropertyBinding)]
        public object Source
        {
            get { return GetValue(SourceProperty); }
            set { SetValue(SourceProperty, value); }
        }

#if (WINRT)
        
        [Category("Common Properties")]
        [CustomPropertyValueEditor(CustomPropertyValueEditor.PropertyBinding)]
        public Binding SourceBinding
        {
            get { return GetBinding(SourceProperty); }
            set { SetBinding<Object>(SourceProperty, value); }
        }

#endif
        
#endregion

#region Handlers

        protected override void OnAttached()
        {
            base.OnAttached();
        }

        private static void OnSourceChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((ValueChangedTrigger)d).OnChange(e.NewValue);
        }

        private void OnChange(Object sourceValue)
        {
            if (this.AssociatedObject == null) return;      // this is to ensure with initial/static set properties the trigger isn't invoked
            base.InvokeActions(sourceValue);
        }

#endregion

    }
}
